package jddk;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;

public class Sync {

	private static final Map<String, String> testMap = new ConcurrentHashMap<>();

	private Object LOCK = new Object();

	public static void main(String[] args) {

		//		synchronized (Sync.class) {
		//
		Sync sync = new Sync();

		for (int i = 0; i < 10; i++) {
			Thread ss = new Thread(new Runnable() {
				@Override
				public void run() {
					sync.testSync();
				}
			}, "sync-thread-" + i);
			ss.start();
		}

	}

	private void testSync() {
		String name = testMap.get("guo");

		if (StringUtils.isBlank(name)) {
			synchronized (LOCK) {

				//同步的代码块中
				//先判断是不是存在, 存在直接返回, 不存在则初始化

				name = testMap.get("guo");
				if (StringUtils.isBlank(name)) {
					System.out.println("==========开始初始化=========" + Thread.currentThread().getName());
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
					}
					testMap.put("guo", "12");
				}
			}

		}

		System.out.println(Thread.currentThread().getName() + "name: " + testMap.get("guo"));
	}

}
